<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>  
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card shadow="hover">
      <!-- 提示区域 -->
      <el-alert show-icon :closable="false" center title="添加商品信息！" type="info" effect="dark"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps  align-center :space="200" :active="activeIndex-0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图品"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <el-form :model="addForm" :rules="addFormRules"  label-position="top" ref="addFormRef" label-width="100px" >
        <el-tabs :before-leave="beforeTabLeave" @tab-click="tabClicked" v-model="activeIndex" :tab-position="'left'" >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name" ></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="props"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="(item,index) in manyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox  border v-for="(item2,index2) in item.attr_vals " :key="index2" :label="item2"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="(item,index) in onlyTableData" :key="item.attr_id" :label="item.attr_name" >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图品" name="3">
            <!-- action表示图片上传到的后台api地址 绝对路径的服务器地址 -->
            <!-- on-preview预览事件 -->
            <!-- on-remove点击x号触发的事件 -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button  @click="add" type="primary" class="add-goods-btn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 图片预览区域 -->
      <el-dialog title="图片预览" :visible.sync="picDialogTableVisible" width="50%">
        <img :src="previewPath" alt="" class="pre-img">
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import _ from 'lodash'
import {getCateListReq,paramsReq,addGoodsReq} from '../../networks/goods'
export default {
  name:'AddGoods',
  created() {
    this.getCateList();
  },
  data() {
    return {
      activeIndex:"0",
      //表单数据对象
      addForm:{
        goods_name:'',
        goods_price:0,
        goods_weight:0,
        goods_number:0,
        //商品分类数据，和级联的selectedKey数组绑定
        goods_cat:[],
        //上传图片的临时路径
        pics:[],
        //商品介绍
        goods_introduce:'',
        // 动态参数和静态属性
        attrs:[],
      },
      //表单规则对象
      addFormRules:{
        goods_name:[{ required: true, message: '请输入商品名称', trigger: 'blur' },],
        goods_price:[{ required: true, message: '请输入商品价格', trigger: 'blur' },],
        goods_weight:[{ required: true, message: '请输入商品重量', trigger: 'blur' },],
        //与级联和表单绑定
        goods_cat:[{ required: true, message: '请输入商品分类', trigger: 'blur' },],


      },
      //商品列表
      cateList:[],
      //级联选择器props配置
      props:{
        expandTrigger: 'hover', 
        label:'cat_name',
        value:'cat_id',
        children:'children'
      },
      // 参数数据
      manyTableData:[],
      // 属性数据
      onlyTableData:[],
      //上传的图片地址
      uploadUrl:"http://timemeetyou.com:8889/api/private/v1/upload",
      headersObj:{
        Authorization:window.sessionStorage.getItem("token"),
      },
      // 图片的路径
      previewPath:'',
      //控制图片预览的显示
      picDialogTableVisible:false,
    }
  },
  computed:{
    cateId(){
      if(this.addForm.goods_cat.length===3){
        return this.addForm.goods_cat[2];
      }else{
        return null;
      }
    }
  },
  methods: {
    //获取商品分类
    getCateList(){
      getCateListReq().then(res=>{
        console.log(res,"getCateListReq");
        if(res.meta.status!==200) return this.$message.error("获取失败！");
        this.cateList=res.data;
        this.$message.success("获取商品分类成功！")
        // console.log(this.cateList,"this.cateList");
      });
    },
    //级联选择器放生变化触发这个函数
    handleChange(){
      console.log(this.addForm.goods_cat);
      //控制级联选择器只显示三级
      if(this.addForm.goods_cat.length!==3){
        //清空选择器
        this.addForm.goods_cat=[];
      }
    },
    // 将要切换标签触发的函数
    beforeTabLeave(activeName,oldActiveName){
      // console.log("即将离开的标签页",oldActiveName);
      // console.log("即将进入的标签页",activeName);
      // return false;
      if(oldActiveName==="0" && this.addForm.goods_cat.length!==3){
        this.$message.error("请先选择商品分类！");
        return false;
        
      }
    },
    // 当tab被点击时触发
    tabClicked(){
      console.log(this.activeIndex);
      //动态参数
      if(this.activeIndex==="1"){
         //发送请求
        paramsReq(`categories/${this.cateId}/attributes`,{sel:"many"}).then(res=>{
          console.log(res,"paramsReq");
          if(res.meta.status!==200) return this.$message.error("获取参数失败！");
          this.$message.success("获取参数成功！");
          //将attr_vals先转化为数组
          res.data.forEach(item=>{
            item.attr_vals=item.attr_vals.length!==0?item.attr_vals.split(","):[];
          })
          this.manyTableData=res.data;
        })
        //静态属性
      }else if(this.activeIndex==="2"){
          paramsReq(`categories/${this.cateId}/attributes`,{sel:"only"}).then(res=>{
          console.log(res,"paramsReq");
          if(res.meta.status!==200) return this.$message.error("获取参数失败！");
          this.$message.success("获取参数成功！");
          this.onlyTableData=res.data;
        })
      }
   
    },
    //图片预览事件
    handlePreview(file){
      console.log(file,"handlePreview");
      this.previewPath=file.response.data.url;
      this.picDialogTableVisible=true;
    },
    //图片删除事件
    handleRemove(file){
      console.log(file);
      //拿到临时路径
      const filePath=file.response.data.tmp_path;
      console.log(filePath,"filePath");
      //删除表单数据中的临时路径
      // 查询该项的下标
      const i = this.addForm.pics.findIndex(x=>{
        x.pic===filePath;
      })
      //移除
      this.addForm.pics.splice(i,1);
      console.log(this.addForm);
    },
    //文件上传成功触发
    handleSuccess(response){
      console.log(response,"handleSuccess");
      //拼接图片信息对象
      const picInfo={pic:response.data.tmp_path}
      //push数组
      this.addForm.pics.push(picInfo);
      console.log(this.addForm);
    },
    //商品添加按钮的点击
    add(){
      console.log(this.manyTableData,"manyTableData");
      console.log(this.onlyTableData,"onlyTableData");
      this.$refs.addFormRef.validate(valid=>{
        console.log(valid);
        if(!valid){
          this.$message.error("请填写必要的表单项目！");
        }else{
          // 提交表单
          //先处理goods_cat数据，为字符串
         const newForm= _.cloneDeep(this.addForm);
         newForm.goods_cat=newForm.goods_cat.join(",");
         console.log(newForm);
         //处理动态参数数据
          //manyTableData，onlyTableData
          this.manyTableData.forEach(item=>{
            const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals.join(",")};
            this.addForm.attrs.push(newInfo);
          });
          // 处理静态参数数据
          this.onlyTableData.forEach(item=>{
            const newInfo={attr_id:item.attr_id,attr_value:item.attr_vals};
            this.addForm.attrs.push(newInfo);
          });
          // newForm.goods_cat=newForm.goods_cat.split(",");
          newForm.goods_price=parseInt(newForm.goods_price);
          newForm.goods_number=parseInt(newForm.goods_number);
          newForm.goods_weight=parseInt(newForm.goods_weight);
          newForm.attrs=this.addForm.attrs;
          console.log(newForm,"newForm");
          //发起请求
          addGoodsReq(newForm).then(res=>{
            console.log(res,"addGoodsReq");
          })

        }
      })
    }
  },
}
</script>
<style scoped>
.el-card{
  margin-top: 15px;
}
.el-alert{
  margin-bottom:15px
}
.el-checkbox{
  margin:0 5px 0 0 !important;
}
.pre-img{
  width:100%;
}
.add-goods-btn{
  margin-top: 15px;
}
</style>